//
//  WHUserAccountViewModel.swift
//  WHSinaWeiBo
//
//  Created by 王寒 on 16/4/9.
//  Copyright © 2016年 wanghan. All rights reserved.
//

import UIKit

let userInfoKey = "com.devwhan.weibo"

//处理业务逻辑,网络请求,数据缓存
class WHUserAccountViewModel: NSObject {

    //单例对象
    static let sharedAccountViewModel: WHUserAccountViewModel = WHUserAccountViewModel()
    
    var accountModel: WHUserAccount?
    
    var userLogin: Bool{
        
        if let u = accountModel where u.expires_data?.compare(NSDate()) == NSComparisonResult.OrderedDescending{

            return true
        }
        
        accountModel = nil
        return false
    }
    
    //私有化构造函数
    private override init() {
        super.init()
        accountModel = self.loadUserInfo()
    }
    
    //头像URL属性
    var headUrl: NSURL?{
  
        let url = NSURL(string: accountModel?.avatar_large ?? "")

        return url
    }

    
}


//MARK:用户登录相关网络请求
extension WHUserAccountViewModel{
    
    //MARK:使用授权码 请求acceesstoken
    func loadAccessToken(code: String,finished: (isSuccess: Bool) -> ()){
        
        HMNetworkTools.tool.loadAccessToken(code) { (result, error) -> () in
            if error != nil{
                print(error)
                return
            }
            
            print("授权成功")
            //获取用户信息方法
            self.loadUserInfo(result!,finished: finished)
        }
        
    }
    
    
    //获取用户信息
    private func loadUserInfo(result: AnyObject,finished: (isSuccess: Bool) -> ()){
        
        guard let dict = result as? [String: AnyObject] else{
            
            finished(isSuccess: false)
            return
        }
        
        let token = dict["access_token"]
        let uid = dict["uid"]

        
        HMNetworkTools.tool.loadUserInfo(token!, uid: uid!) { (responObject, error) -> () in
            
            
            if error != nil{
                print(error)
                finished(isSuccess: false)
                return
            }
            
            //接受的数据
            guard var userInfoDict = responObject as? [String : AnyObject] else{
                finished(isSuccess: false)
                return
            }
            
            //拼接两次结果
            for (k,v) in dict{
                userInfoDict[k] = v
            }
            
            //保存
            self.saveUserAccount(userInfoDict)

            //成功
            finished(isSuccess: true)

        }
    }
    
    
}


//存储数据,获取数据
extension WHUserAccountViewModel{
    
    //保存数据
    func saveUserAccount(userInfoDict: [String : AnyObject]){
        
        
        //字典转模型
        let account = WHUserAccount(dict: userInfoDict)
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_data"]
        let accountDict = account.dictionaryWithValuesForKeys(keys)
        
        //保存数据成功后 将登录状态设置为true
        self.accountModel = account
        //偏好设置
        let userDefaults = NSUserDefaults.standardUserDefaults()
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        userDefaults.synchronize()
        
    }
    
    
    //读取数据
    func loadUserInfo() -> WHUserAccount? {
        
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            return nil
        }
        let account = WHUserAccount(dict: dict)
        return account
        
    }
    
    
}

